//
//  CarsViewController.m
//  FuelLog
//
//  Created by Pure Mass Communications on 9/1/08.
//  Copyright 2008 . All rights reserved.
//
//  Placed under GPL v2 with the kind permission of Pure Mass Communications
//
//  Modified to make compile under SDK 3.1 by Olaf Greck in May 2010
//
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import "CarsViewController.h"
#import "FuelLogAppDelegate.h"
#import "FuelLogViewController.h"
#import "AddCarViewController.h"
#import "LoginViewController.h"
#import "CarCell.h"

//#import "Car.h" // needed in 3.0 for accessoryButtonTappedForRowWithIndexPath ?
#import "DebugOutput.h"

@interface CarsViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end

@implementation CarsViewController


@synthesize fetchedResultsController, managedObjectContext;
@synthesize doneButton, carsButton, prefsButton ,statsButton ,addButton, toolBarSpacer;

/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		// Initialization code
	}
	return self;
}
*/
#pragma mark -
-(id)initWithStyle:(UITableViewStyle)style {
	debug(@"in initWithStyle");
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    	doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
									   //style:UIBarButtonItemStylePlain
									   target:self
									   action:@selector(chooseCar:)];
		self.navigationItem.rightBarButtonItem = doneButton;
		carsButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Auto2.png"]
													   style:UIBarButtonItemStyleBordered
													 target:self
											 action:nil];
		prefsButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"19-gear.png"]
													   style:UIBarButtonItemStyleBordered
													  target:self
													  action:nil];
		statsButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"graph.png"]
													   style:UIBarButtonItemStyleBordered
													  target:self
													  action:nil];
		addButton = [[UIBarButtonItem alloc ] initWithImage:[UIImage imageNamed:@"plus.png"]
																	style:UIBarButtonItemStyleBordered
													   target:self
													   action:@selector(addCar:)];
		carsButton.enabled = NO;
		prefsButton.enabled = NO;
		statsButton.enabled = NO;
		addButton.enabled = YES;
		toolBarSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
																					   target:self
																					   action:nil];
		[self setToolbarItems:[NSArray arrayWithObjects:carsButton, 
							   toolBarSpacer, prefsButton,
							   toolBarSpacer, statsButton,
							   toolBarSpacer, addButton,
							   nil] animated:NO];
 
	}
	return self;

}
 
- (void)setupHeader {	
	//
    // Create a header view. Wrap it in a container to allow us to position
    // it better.
    //
	//*
    UIView *containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, 60)] autorelease];
    UILabel *headerLabel =	[[[UILabel alloc] initWithFrame:CGRectMake(10, 20, self.tableView.bounds.size.width, 40)] autorelease];

	headerLabel.text = NSLocalizedString(@"Import", @"") ;
	headerLabel.textAlignment = UITextAlignmentCenter;
    headerLabel.textColor = [UIColor blackColor];
	//    headerLabel.shadowColor = [UIColor blackColor];
	//    headerLabel.shadowOffset = CGSizeMake(0, 1);
    headerLabel.font = [UIFont boldSystemFontOfSize:22];
    headerLabel.backgroundColor = [UIColor clearColor];
    [containerView addSubview:headerLabel];
    self.tableView.tableHeaderView = containerView;
	
	// */
}

/*
 Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
}
 */


- (void)viewDidLoad {
	debug(@"in viewDidLoad");
    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {
        
        debug(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
	debug(@"%d objects fetched", [[fetchedResultsController fetchedObjects] count]);
	
	
 	[self setupHeader]; 

}

#pragma mark -
- (void)viewWillAppear:(BOOL)animated {
	//	[self setupHeader];  
	
	[self.tableView reloadData];
	[super setEditing:NO animated:NO];
		debug(@"in viewWillAppear");
  
}
 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    debug(@"in configureCell");
	
	NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text =[[managedObject valueForKey:@"Name"] description];
	debug(@"managedObject %@",managedObject); 
	
	cell.detailTextLabel.text = @"Detail"; //[[managedObject valueForKey:@"ID"] description];
}
#pragma mark -

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
//	[tableView release];
	[doneButton release];
	[carsButton release];
	[prefsButton release];
	[statsButton release];
	[addButton release];
	[toolBarSpacer release];
	[super dealloc];
}

-(IBAction)addCar:(id)sender {
//	AddCarViewController *addController = [FuelLogViewController addCarViewController];
	AddCarViewController *addController =  [[[AddCarViewController alloc] initWithNibName:nil bundle:nil]
											autorelease];
	Car *car = [[Car alloc] init];
	[addController setCar:car];
	[addController setLabel];
//	[self presentModalViewController:addController animated:YES];
	[self.navigationController pushViewController:addController animated:YES];

}

-(IBAction)chooseCar:(id)sender {
//obsolete: from ModaViewController	[self dismissModalViewControllerAnimated:YES];
	[self.navigationController popViewControllerAnimated:YES];
}

-(IBAction)importCar:(id)sender {
	debug(@"in importCar");
	[self presentModalViewController:[FuelLogViewController filesViewController] animated:YES];
}
 
#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {
    
    if ( fetchedResultsController != nil) {
        return  fetchedResultsController;
    }
	
    /*
     Set up the fetched results controller.
	 */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//	NSPredicate * predicate = [NSPredicate predicateWithFormat:@"Selected = 0"];// , self.predicateString];
	[fetchRequest setPredicate:nil];
	
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    
    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];
    
    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;
    
    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];
    
    return fetchedResultsController;
}    


#pragma mark -
#pragma mark Fetched results controller delegate


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
    
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
    
    UITableView *tableView = self.tableView;
    
    switch(type) {
            
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;
            
        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView endUpdates];
}


/*
 // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. 
 
 - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
 // In the simplest, most efficient, case, reload the table view.
 [self.tableView reloadData];
 }
 */


#pragma mark - UITableView delegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
/*	int returnValue = 1;
	if (section == 1) {
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
    debug(@"count of cars %d",appDelegate.cars.count);
	returnValue = appDelegate.cars.count;
	}
	return returnValue;
*/
 	 return [[fetchedResultsController fetchedObjects] count];

 }

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 	NSInteger row = indexPath.row;
	NSInteger section = indexPath.section;

	CarCell *carCell = (CarCell *)[tableView dequeueReusableCellWithIdentifier:@"CarCell"];
    if ((carCell == nil) && (section ==1)) {
        // Create a new cell. CGRectZero allows the cell to determine the appropriate size.
//        carCell = [[[CarCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"CarCell"] autorelease];
        carCell = [[[CarCell alloc] initWithFrame:CGRectZero ] autorelease];
		carCell.master = self;
    }
	else{
	carCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"] autorelease];
	}
	if (section ==0) {
		carCell.accessoryType = UITableViewCellAccessoryNone;
		carCell.textLabel.text =  (NSLocalizedString(@"Import", @""));
		carCell.backgroundColor = [UIColor whiteColor];
		carCell.textLabel.textColor = [UIColor blackColor];
		carCell.textLabel.textAlignment = UITextAlignmentCenter;
	}
	else {
    // Retrieve the car object matching the row from the application delegate's array.
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
    Car *car = (Car *)[appDelegate.cars objectAtIndex:indexPath.row];
	carCell.car = car;
	}
    return carCell;
}
*/

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"Cell";
	UITableViewCell * carCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (carCell == nil) {
		carCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
	}
	carCell.imageView.image = [UIImage imageNamed:@"unchecked.png"];
	
	if (indexPath.section ==0) {
		carCell.accessoryType = UITableViewCellAccessoryNone;
		carCell.textLabel.text =  (NSLocalizedString(@"Import", @""));
		carCell.backgroundColor = [UIColor whiteColor];
		carCell.textLabel.textColor = [UIColor blackColor];
		carCell.textLabel.textAlignment = UITextAlignmentCenter;
		carCell.imageView.image = nil;
	}
	else {
		carCell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
		// Retrieve the car object matching the row from the application delegate's array.
		FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
		Car *car = (Car *)[appDelegate.cars objectAtIndex:indexPath.row];
		carCell.textLabel.text =  car.label;
		if (car.selected == 1) carCell.imageView.image = [UIImage imageNamed:@"checked.png"];
//		carCell.detailTextLabel.text = [NSString stringWithFormat:@"%d",car.selected];
	}
	return carCell;
	
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//	NSInteger row = indexPath.row;
	debug(@"in didSelectRowAtIndexPath");
	NSInteger section = indexPath.section;
	if (section == 0) {
		[self importCar:nil];
	}
	else {
		// first make uncheck all cars
		FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
		NSArray *cells = appDelegate.cars;
		for(int i = 0; i < cells.count; ++i) {
			Car *theCar = (Car *)[appDelegate.cars objectAtIndex:i];
			[theCar setSelected:NO];
		}
		Car *car = (Car *)[appDelegate.cars objectAtIndex:indexPath.row];
		[car setSelected:YES];
		[appDelegate setCurrentCar:car];
		debug(@"seecting auto %@, %d", car.label, car.selected);
		[self.tableView reloadData];
//		CarCell *carCell = (CarCell *)[tableView cellForRowAtIndexPath:indexPath];
//		[carCell checkAction:nil];
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark Another iPhone bug: the checked image shows up on the wrong row 

- (void)clickSelectedCar {
	debug(@"in clickSelectedCar");
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSUInteger idx[] = {0, 0};
	int i;
	for (i=0; i<[appDelegate.cars count]; ++i) {
		if (((Car *)[appDelegate.cars objectAtIndex:i]).selected) {
			idx[1] = i;
			break;
		}
	}
//	[self.tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathWithIndexes:idx length:2]];
}

#pragma mark -
// OS 3.0+ only otherwise see - (void)onClick:(id)sender in CarCell.m
//*
 - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	debug(@"in accessoryButtonTappedForRowWithIndexPath");
	AddCarViewController *addController =  [[[AddCarViewController alloc] initWithNibName:nil bundle:nil] autorelease]; 
	 NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
	 [addController setCar:[[managedObject valueForKey:@"Name"] description]];

	 
	[addController setLabel];

	 
	 [self.navigationController pushViewController:addController animated:YES];
}
// */
@end
